<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { PlusColumn } from 'plus-pro-components'

import { useAccreditSysUser } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const { isPending, mutate } = useAccreditSysUser()

const detailValue = defineModel<any>('detailValue')

const id = defineModel<any>('id')

const visible = defineModel<boolean>('visible', { required: true })

const dialog = '授权账号'

const formRef = ref()

const initialState = {
    applys: '',
    password: '',
    personsjhm: '',
    personsszzname: '',
    userName: '',
}

const state = ref<any>(cloneDeep(initialState))

// const applysOptions = computed(() => {
//     return Number(state.value?.persondwlx) === 11 ? [{ label: '招采平台', value: 2 }] : [{ label: '集采商城', value: 1 }, { label: '招采平台', value: 2 }]
// })

const isAccredit = computed(() => state.value?.isAccredit === '1') // 已授权

const columns = computed<PlusColumn[]>(() => {
    return [
        {
            label: '所属企业账号',
            prop: 'personsszzname',
            valueType: 'text',
        },
        {
            label: '手机号',
            prop: 'personsjhm',
            valueType: 'text',
        },
        {
            label: '用户名',
            prop: 'userName',
            valueType: isAccredit.value ? 'text' : 'input',
        },
        {
            hideInForm: isAccredit.value,
            label: '密码',
            prop: 'password',
        },
        // {
        //     fieldProps: {
        //         multiple: true,
        //     },
        //     label: '关联应用',
        //     options: applysOptions.value,
        //     prop: 'applys',
        //     valueType: 'select',
        // },
    ]
})

function validatea3(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入用户名'))
    }
    if (pattern.test(value))
        callback(new Error('用户名不允许输入空格'))

    else
        callback()
}

function validatea4(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,._])[\w!@#$%^&*,\\.]{6,20}$/
    if (!value) {
        callback(new Error('请输入密码'))
    }
    if (!pattern.test(value))
        callback(new Error('密码必须包含大小写字母，特殊字符和数字，且长度不低于6位'))

    else
        callback()
}

const rules = {
    applys: [
        {
            message: '请选择关联应用',
            required: true,
        },
    ],
    password: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validatea4,
        },
    ],
    userName: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validatea3,
        },
    ],

}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
    state.value = cloneDeep(initialState)
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            // applys: state.value?.applys,
            id: state.value?.id,
            orgId: state.value?.personsszz,
            orgName: state.value?.personsszzname,
            password: state.value?.password,
            phone: state.value?.personsjhm,
            userName: state.value?.userName,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

watchEffect(() => {
    if (id.value && detailValue.value) {
        state.value = cloneDeep(detailValue.value)
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="800"

                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="130"
                  :has-footer="false"
                  :rules="isAccredit ? {} : rules"
                  class="max-h-600 overflow-x-hidden overflow-y-auto"
                  :row-props="{ gutter: 20 }"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn v-if="!isAccredit"
                           type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
